package cn.edu.scau.cmi.linjinyong.fxml.mybatis;

import cn.edu.scau.cmi.linjinyong.mybatis.dao.StudentDao;
import cn.edu.scau.cmi.linjinyong.mybatis.dao.TeacherDao;
import cn.edu.scau.cmi.linjinyong.mybatis.domain.Student;
import cn.edu.scau.cmi.linjinyong.mybatis.factory.SessionFactory;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class SelectStudentController {
    @FXML
    private TableView<StudentData> studentDataTableView;
    @FXML
    private TableColumn<StudentData, Long> studentIdColumn;
    @FXML
    private TableColumn<StudentData, String> studentNameColumn;
    @FXML
    private TableColumn<StudentData, String> studentHaveBeenChoosedColumn;

    private ObservableList<StudentData> studentDataObservableList;
    @FXML
    private Button submitButton;

    private SqlSession sqlSession = SessionFactory.getSession();
    private StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
    private TeacherDao teacherDao = sqlSession.getMapper(TeacherDao.class);

    @FXML
    private void initialize(){
        studentDataObservableList = FXCollections.observableArrayList();
        List<Student> students = studentDao.listSelectableStudentsByTid(MybatisController.getTeacher().getId());
        ArrayList<StudentData> studentData = new ArrayList<>(students.size());
        students.forEach(s->{
            studentData.add(new StudentData(s));
        });
        studentDataObservableList.addAll(studentData);
        studentIdColumn.setCellValueFactory(new PropertyValueFactory<StudentData, Long>("id"));
        studentNameColumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("name"));
        studentHaveBeenChoosedColumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("haveBeenChoosed"));
        studentDataTableView.setItems(studentDataObservableList);
    }

    @FXML
    public void clickTableView() {
        StudentData selectedstudent = studentDataTableView.getSelectionModel().getSelectedItem();
        if(selectedstudent != null) {
            MybatisController.getStudent().setId(selectedstudent.getId());
            submitButton.setDisable(false);
        }
    }

    @FXML
    private void clickSubmitButton(){
        studentDao.chooseStudent(MybatisController.getStudent().getId());
        sqlSession.commit();
        Stage stage = (Stage) submitButton.getScene().getWindow();
        stage.close();
    }
}
